var gui = {
    add_marker_btn : '',
    edit_window: '',
    info_window: '',
    picinfo : '',
};

function get_pid(){
    params = getUrlParams();
    var pid = params['pid'];
    return pid;
}
function is_readonly(){
    params = getUrlParams();
    return params['readonly'];
}

$(function(){
    var pid = get_pid();
    $.get('/picinfo.php?pid='+pid, 
        '',  function(data) {
            log(data);
            p = JSON2.parse(data);
            gui.picinfo = p;
            log(p);
            $('#img').attr('src', p.url)
                .load(update_container_size);
            for (i in p.marks){
                log(p.marks[i]);
                draw_marker(p.marks[i]);
            }
            if(is_readonly())
                set_readonly();
        });
    function update_container_size(){
        $('#container').css({ 
            'height' : $('#img')[0].clientHeight ,
            'width' : $('#img')[0].clientWidth ,
        });
        $('#container').css('overflow','hidden');
    }
});

function save(){
    markers = get_all_marker();
    log(JSON2.stringify(markers));
    var pid = get_pid();

    $.ajax({
      type: 'POST',
      url: 'mark.php?pid='+pid,
      data: JSON2.stringify(markers),
      success: function(){ },
      dataType: 'json'
    });
}


$(function(){
    gui.add_marker_btn = $("#add_marker");
    gui.add_marker_btn.disable = function(){
        gui.add_marker_btn.unbind('click');
        gui.add_marker_btn.addClass('button_disable');
    };
    gui.add_marker_btn.enable = function(){
        gui.add_marker_btn.removeClass('button_disable');
        gui.add_marker_btn.click(function(){
            gui.add_marker_btn.disable() ;
            create_marker();
        });
    };
    gui.add_marker_btn.enable();

    $("#finish_btn").click(function(){
        save();
    });
    $("#preview_btn").click(function(){
        save();
        url = window.location + "&readonly=1";
        window.open(url, 'preview window');
    });
});

$(function(){
    gui.edit_window = $("#edit_tooltip");
    gui.edit_window.show = function(trigger){
        //1.caculate postion
        var top = trigger.offset().top;
        var left = trigger.offset().left;
        top -= gui.edit_window.outerHeight() ;
        left -= (gui.edit_window.outerWidth() - trigger.outerWidth())/2;
        gui.edit_window.css({position:'absolute', top: top, left: left, display:"block"});  
        //2. init data

        $('#edit_link').val(trigger.attr('_link'));
        $('#edit_title').val(trigger.attr('_title'));
        $('#edit_tag').val(trigger.attr('_tag'));
        gui.edit_window.reset_tagbtn();
        //3. bind event
        $("#edit_cancel_btn").unbind("click")
        .click(function(){
            gui.edit_window.hide();
        });
        $("#edit_remove_btn").unbind("click")
        .click(function(){
            gui.edit_window.hide();
            trigger.remove();
        });
        $("#edit_ok_btn").unbind("click")
        .click(function(event){
            event.preventDefault();
            var urlRe = /^(https?:\/\/)?[\da-z\.\-]+\.[a-z\.]{2,6}[#&+_\?\/\w \.\-=]*$/i,
            
            link = $('#edit_link').val(); 
            title = $("#edit_title").val(); 
            tag = $("#edit_tag").val()
            if (!$("#edit_form").data("validator").checkValidity())
                return;
            trigger.attr('_link', link);
            trigger.attr('_title', title)
            trigger.attr('_tag', tag);
            gui.edit_window.hide();
        });
    };
    gui.edit_window.hide = function(){
        gui.edit_window.css({display:"none"});  
        $('.error').css("display", "none");
    }

    gui.edit_window.reset_tagbtn = function(){
        $(".tagbtn").addClass('tagbtn_normal')
        .unbind('click')
        .bind ('click', function(e){
            old = $("#edit_tag").val();
            $("#edit_tag").val(old + " " + e.target.innerHTML);
            $(e.target).removeClass('tagbtn_normal').addClass('tagbtn_selected');
            $(e.target).unbind('click');
        });
        tags = $(".tagbtn");
        already_tag = $("#edit_tag").val();
        for (i=0; i< tags.length; i++){
            t = $(tags[i]);
            if(already_tag.indexOf(tags[i].innerHTML) != -1){
                t.removeClass('tagbtn_normal').addClass('tagbtn_selected');
                t.unbind('click');
            }
        }
    }
});

//function marker_click_handler(event, ui){

    ////$('#tag').val()
    //element = $(event.target);
    //$('#link').val(element.attr('_link') || 'http://');
    //$('#title').val(element.attr('_title'));
    //$('#tag').val(element.attr('_tag'));


    //$( "#dialog-form" ).dialog( "option", 'buttons', {
        //"OK" : function (){
            //$( this ).dialog( "close" );
            //link = $('#link').val(); 
            //title = $("#title").val(); 
            //tag = $("#tag").val()
            //log($("#info_tooltip").html());
            //$(event.target)
                //.attr('_link', link)
                //.attr('_title', title)
                //.attr('_tag', tag);

            //create_popup($(event.target));
            //log($("#info_tooltip").html());
        //},
        //"Close" : function(){
            //$( this ).dialog( "close" );
        //},

    //});
    //$( "#dialog-form" ).dialog( "open" );
//}



function set_info_tag(tags){
    $("#info_tags").html("");
    arr = tags.split(' ');
    for (i in arr){
        $('<span class="tagbtn tagbtn_normal">'+arr[i]+'</span> ').appendTo("#info_tags");
    }
}

function create_popup(element){
    element.removeData("tooltip");//hack
    element.tooltip({
        tip: '#info_tooltip',
        onShow: function(event) {
            log(event);
            $("#info_tooltip_link").attr('href', element.attr('_link'));
            $("#info_tooltip_title").text(element.attr('_title'));
            $("#info_tooltip_tag").text(element.attr('_tag'));
            set_info_tag(element.attr('_tag'));
        },
    });
    element.click(function(event){
        gui.edit_window.show($(event.target));
    });
}

function draw_marker(info){
    cnt = $('.marker').length ;
    marker_id = 'marker' + cnt 
    marker_logo_y = cnt * -25;

    var new_marker = $('<span></span>', {id: marker_id})
        .addClass('marker')
        .attr('_link', info.link)
        .attr('_title', info.title)
        .attr('_tag', info.tag)
        .css('background-position', '0px '+ marker_logo_y +'px')
        .css('left', info.x)
        .css('top', info.y)
        .appendTo("#container");
    //var f = new create_popup();
    create_popup(new_marker);
    $( ".marker" ).draggable({
        opacity: 0.35 ,
        containment: 'parent',
    });
}

function create_marker(){
    cnt = $('.marker').length ;
    marker_id = 'marker' + cnt 
    marker_logo_y = cnt * -25;

    var new_marker = $('<span></span>', {id: marker_id})
        .addClass('marker')
        .attr('_link', 'http://')
        .attr('_title', '')
        .attr('_tag', '')
        .css({'background-position': '0px '+ marker_logo_y +'px' ,
            "display": "none"
        })
        .appendTo("#container");

    $("#container").bind('mousemove', function(e){
            if ($(e.target).hasClass('marker') )
                return;
            var xx=e.originalEvent.layerX || e.originalEvent.x||0;
            var yy=e.originalEvent.layerY||e.originalEvent.y||0;
            if (xx-12 < 0)
                return;
            if(yy-30 < 0)
                return;

            new_marker.css({'top': yy-30+'px' })
                .css({'left': xx-12+'px' })
            new_marker.css({'display': 'block'});
        })

    $("#container").click(function(e){
            if ($(e.target).hasClass('marker') )
                return;

            gui.add_marker_btn.enable();
            $("#container").unbind("mousemove");
            $("#container").unbind("click");
            create_popup(new_marker);
            //new_marker.bind("click", marker_click_handler);
            new_marker.click(); //trigger event

            var xx=e.originalEvent.layerX || e.originalEvent.x||0;
            var yy=e.originalEvent.layerY||e.originalEvent.y||0;
            //log(xx+":" + yy);
            new_marker.css({'top': yy-30+'px' })
                .css({'left': xx-12+'px' })
        })


    $( ".marker" ).draggable({
        opacity: 0.35 ,
        containment: 'parent',

        start: function(event, ui) {
            //ui.helper.unbind("click", marker_click_handler);
        },
        stop: function(event, ui) {
            setTimeout(function(){
                //ui.helper.bind("click", marker_click_handler);
            }, 300);
        }
    });
}

//得到最后需要post的list
function get_all_marker(){
    markers = $('.marker');
    var list = new Array();
    for(i=0;i<markers.length;i++){
        mm = $(markers[i]);
        var o = {
            'link': mm.attr('_link'),
            'title': mm.attr('_title'),
            'tag': mm.attr('_tag'),
            'y': mm.css('top'),
            'x': mm.css('left'),
        }
        list.push(o);
    }
    return list;
}

function set_readonly(){
    $(".marker")
        .draggable("disable")
        .unbind("click");
    $(".mbox").css("display", "none");
    if (gui.picinfo.next.id){
        var url = window.location.href.replace(get_pid(), gui.picinfo.next.id);
        $("#nextpage").css('display', 'block')
            .attr('href', url);
    }
    if (gui.picinfo.prev.id){
        var url = window.location.href.replace(get_pid(), gui.picinfo.prev.id);
        $("#prevpage").css('display', 'block')
            .attr('href', url);
    }

}
